<template>
  <div class="blog-container" v-if="listData.length > 0">
    <a-list
      item-layout="vertical"
      size="large"
      :data-source="listData"
      :loading="loading || loadingMore"
      @scroll="handleScroll"
    >
      <template #renderItem="{ item }">
        <a-list-item class="card">
          <!-- 上部分：作者信息 + 时间 -->
          <div class="blog-header">
            <a-avatar
              :src="item.authorAvatar"
              :size="48"
              @click="() => handleUserClick(item.userId)"
            />
            <div class="author-info">
              <span class="username">{{ item.author }}</span>
              <span class="time">{{ item.createdAt }}</span>
            </div>
            <a-button
              v-if="!item.isMyself"
              @click="followAuthor(item.userId, item.isFollowed)"
              class="follow-button"
            >
              {{ item.isFollowed ? "已关注" : "关注" }}
            </a-button>
            <div class="blog-setting" v-if="item.isMyself">
              <span class="pk" style="color: #b8b8b8; margin-right: 5px">{{
                item.privateKey
              }}</span>
              <a-dropdown :trigger="['click']">
                <a class="ant-dropdown-link" @click.prevent>
                  <DownOutlined />
                </a>
                <template #overlay>
                  <a-menu>
                    <a-menu-item
                      key="0"
                      @click="() => handlePkUpdated(item.id, 0)"
                    >
                      <a>转为公开</a>
                    </a-menu-item>
                    <a-menu-item
                      key="1"
                      @click="() => handlePkUpdated(item.id, 2)"
                    >
                      <a>转为粉丝/好友可见</a>
                    </a-menu-item>
                    <a-menu-item
                      key="2"
                      @click="() => handlePkUpdated(item.id, 1)"
                    >
                      <a>转为仅自己可见</a>
                    </a-menu-item>
                    <a-menu-divider />
                    <a-menu-item key="3" @click="handleBlogDelete(item.id)"
                      >删除</a-menu-item
                    >
                  </a-menu>
                </template>
              </a-dropdown>
              <span class="privateKey">{{
                item.privateKey != null
                  ? privateKeyToString(item.privateKey)
                  : privateKeyToString(0)
              }}</span>
            </div>
          </div>

          <!-- 中下部分：内容文案 + 图片 -->
          <div class="blog-content">
            <p>{{ item.content }}</p>

            <!-- 图片区域 -->
            <div
              v-if="item.images && item.images.length > 0"
              class="image-section"
            >
              <!-- 单张图片 -->
              <a-image
                v-if="item.images.length === 1"
                :src="item.images[0]"
                alt="blog image"
                class="single-image"
              />

              <!-- 多张图片九宫格 -->
              <div v-else class="grid-images">
                <a-image
                  v-for="(image, index) in item.images"
                  :key="index"
                  :src="image"
                  alt="blog image"
                  class="grid-item image-item"
                />
              </div>
            </div>
          </div>

          <!-- 操作按钮 -->
          <template #actions>
            <a-button
              v-for="{ icon, textKey } in actions"
              :key="textKey"
              type="text"
              class="action-button"
              @click="handleActionClick(icon, item)"
            >
              <component
                :is="
                  icon === LikeOutlined
                    ? item.liked
                      ? LikeTwoTone
                      : icon
                    : icon
                "
                style="margin-right: 8px"
                class="action-icon"
              />
              {{ item[textKey] || 0 }}
            </a-button>
          </template>
          <div class="comment-wrapper">
            <CommentSection
              v-if="item.id && showComment[item.id]"
              :key="item.id"
              :blog-id="item.id"
              @comment-updated="handleCommentUpdated(item.id, $event)"
            />
          </div>
          <teleport to="body">
            <transition name="like">
              <div v-if="showLikeAnimation" class="like-animation">
                <LikeTwoTone />
              </div>
            </transition>
          </teleport>
        </a-list-item>
      </template>
    </a-list>
  </div>
  <div v-else-if="!loading && listData.length === 0" class="empty-state">
    暂无博客
  </div>
</template>

<script lang="ts" setup>
import { DownOutlined } from "@ant-design/icons-vue";
import {
  LikeOutlined,
  MessageOutlined,
  LikeTwoTone,
} from "@ant-design/icons-vue";
import { getMinioUrlList, getMinioUrl } from "@/utils/minio";
import { ref, onMounted, watch } from "vue";
import { useRoute } from "vue-router";
import {
  createBlog,
  getBlog,
  getFollowBlogList,
  getHotBlogList,
  getMyBlogList,
  getSearchBlogList,
  getUserBlogList,
  isLike,
} from "@/api/blog";
import dayjs from "dayjs";
import { likeBlog, updatePk, deleteBlog } from "@/api/blog";
import { reactive } from "vue";
import CommentSection from "@/components/CommentSection.vue";
import { doFollow, getByBlogId } from "@/api/user";
import router from "@/router";
import { message } from "ant-design-vue";
import { useLoginUserStore } from "@/store/useLoginUserStore";

interface BlogItem {
  id: number;
  userId: number;
  content: string;
  images?: Array<{ url: string }>; // 博客图片数组
  author: string;
  authorAvatar: string;
  likes: number;
  liked: boolean;
  comments: number;
  createdAt: string;
  privateKey: string;
  isMyself: boolean;
  isFollowed: boolean;
}

const searchKey = ref<string>("");
const privateKeyToString = (key: any): string => {
  const num = Number(key);
  if (isNaN(num)) {
    return "";
  }
  switch (num) {
    case 0:
      return "公开";
    case 1:
      return "仅自己可见";
    case 2:
      return "粉丝/好友可见";
    default:
      return "";
  }
};
const formatTime = (timeStr: string): string => {
  return dayjs(timeStr).format("YYYY-MM-DD HH:mm");
};
const showLikeAnimation = ref(false);
const showComment = reactive<Record<number, boolean>>({});
const handleActionClick = async (iconComponent: any, blogItem: BlogItem) => {
  if (!loginUserStore.loginUser?.id) {
    return message.error("请先登录");
  }
  if (iconComponent === LikeOutlined) {
    if (!blogItem.liked) {
      // 点赞
      // 触发点赞动画
      showLikeAnimation.value = true;
      console.log("点赞动画触发", showLikeAnimation.value);
      // 强制等待一帧后重置，保证下次也能触发
      requestAnimationFrame(() => {
        setTimeout(() => {
          showLikeAnimation.value = false;
        }, 500);
      });
      await likeBlog(blogItem.id);
      const updatedBlog = await getBlog(blogItem.id);
      const index = listData.findIndex((item) => item.id === blogItem.id);
      if (index > -1) {
        listData[index].likes = updatedBlog.data.likesCount;
        listData[index].liked = true;
      }
    } else {
      // 取消点赞
      await likeBlog(blogItem.id); // 注意：你可能需要一个 unlike 接口
      const updatedBlog = await getBlog(blogItem.id);
      const index = listData.findIndex((item) => item.id === blogItem.id);
      if (index > -1) {
        listData[index].likes = updatedBlog.data.likesCount;
        listData[index].liked = false;
      }
    }
  } else {
    const current = showComment[blogItem.id];
    showComment[blogItem.id] = !current;
  }
};

const followAuthor = async (authorId: number, isFollowed: boolean) => {
  console.log("关注作者", authorId, isFollowed);
  try {
    const res = await doFollow(authorId);
    if (res.data.code === 200) {
      listData.forEach((blog) => {
        if (blog.userId === authorId) {
          blog.isFollowed = res.data.data.state === 1;
        }
      });
      if (res.data.data.state === 1) {
        console.log("关注成功");
        message.success("关注成功");
      } else if (res.data.data.state === 0) {
        console.log("取关成功");
        message.success("取关成功");
      }
    }
  } catch (error) {
    console.error("关注失败", error);
  }
};

const handleBlogDelete = async (blogId: number) => {
  if (!loginUserStore.loginUser?.id) {
    return message.error("请先登录");
  }
  // 实现删除逻辑
  try {
    await deleteBlog(blogId);
    const index = listData.findIndex((item) => item.id === blogId);
    if (index > -1) {
      listData.splice(index, 1); // 局部删除
    }
  } catch (error) {
    console.error("删除博客失败", error);
  }
};

const handlePkUpdated = async (blogId: number, key: number) => {
  if (!loginUserStore.loginUser?.id) {
    return message.error("请先登录");
  }
  console.log("收到pk", key);
  try {
    await updatePk(blogId, key);
    const index = listData.findIndex((item) => item.id === blogId);
    if (index > -1) {
      listData[index].privateKey = privateKeyToString(key); // 局部更新
    }
  } catch (error) {
    console.error("更新权限失败", error);
  }
};

const handleCommentUpdated = (blogId: number, newCommentCount: number) => {
  if (!loginUserStore.loginUser?.id) {
    return message.error("请先登录");
  }
  const index = listData.findIndex((item) => item.id === blogId);
  if (index > -1) {
    listData[index].comments = newCommentCount;
  }
};

const loading = ref(true);
const loadingMore = ref(false);
const hasMore = ref(true);
const listData = reactive<BlogItem[]>([]);
const route = useRoute();
const fetchSearchResult = async (key: string) => {
  try {
    const basicBlogInfo = await getSearchBlogList(key);
    if (basicBlogInfo?.data && Array.isArray(basicBlogInfo.data)) {
      const likePromises = basicBlogInfo.data.map((item) => isLike(item.id));
      const likedRes = await Promise.all(likePromises);
      // ✅ 统一处理数据
      basicBlogInfo.data.forEach((item, index) => {
        listData.push({
          id: item.id,
          userId: item.userId,
          author: item.username, // ✅ username → author
          authorAvatar: getMinioUrl(
            item.avatar ||
              "/avatar/icon/f9256155491e54bf5e99bf29eece0156_512_512.jpg"
          ), // ✅ avatar → authorAvatar
          content: item.content,
          createdAt: formatTime(item.createdAt), // ✅ 显示时间
          likes: item.likesCount, // ✅ likes → likes
          comments: item.commentsCount, // 示例值，可根据实际接口填充
          images: getMinioUrlList((item.mediaList || []).map((img) => img.url)),
          privateKey: privateKeyToString(item.privateKey), // ✅ privateKey → privateKey
          liked: Boolean(likedRes[index]?.data?.data ?? false), // ✅ 提取每个请求的结果        });
          isMyself: Boolean(item.isMyself),
          isFollowed: Boolean(item.isFollowed),
        });
        console.log("listData", listData);
      });
    }
  } catch (error) {
    console.error("获取热门博客失败", error);
  }
};

onMounted(async () => {
  const key = route.query.q as string;
  if (key) {
    searchKey.value = key;
    await fetchSearchResult(key);
  }
  loading.value = false;
});

const loadMore = async () => {
  if (!hasMore.value || loadingMore.value) return;
  loadingMore.value = true;
  await fetchSearchResult(searchKey.value);
  loadingMore.value = false;
};

const actions = [
  { icon: MessageOutlined, textKey: "comments" },
  { icon: LikeOutlined, textKey: "likes" },
];

const handleScroll = (e: Event) => {
  const target = e.target as HTMLElement;
  if (target.scrollTop + target.offsetHeight === target.scrollHeight) {
    loadMore();
  }
};

const loginUserStore = useLoginUserStore();
const handleUserClick = async (userId: number) => {
  if (!loginUserStore.loginUser?.id) {
    return message.error("请先登录");
  }
  router.push({ path: `/user/${userId}` });
};

watch(
  () => route.query.q,
  async (newQuery) => {
    if (!newQuery) {
      return;
    }
    listData.splice(0);
    await fetchSearchResult(newQuery as string);
  }
);
</script>
<style scoped>
.card {
  background-color: #fff;
  border-radius: 12px;
  padding: 12px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.08);
  margin-bottom: 16px;
}

.blog-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  position: relative;
}

.author-info {
  display: flex;
  flex-direction: column;
  margin-left: 12px;
  height: 48px;
  justify-content: center;
}

.username {
  font-family: "PingFang SC", "Hiragino Sans GB", sans-serif;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.time {
  color: #999;
  font-size: 13px;
  margin-top: 2px;
}

.follow-button,
.blog-setting {
  position: absolute;
  right: 10px;
  top: 30%;
  transform: translateY(-50%);
}

.privateKey {
  color: #999;
  font-size: 13px;
  margin-left: 10px;
}

.blog-content {
  margin-top: 8px;
  margin-left: 60px;
  font-size: 16px;
  color: #222;
}

.image-section {
  width: 80%;
  margin-top: 12px;
}

.single-image {
  width: 100%;
  height: auto;
  border-radius: 8px;
}

.grid-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(125px, 1fr));
  gap: 4px;
  overflow: hidden;
  margin-top: 8px;
}

:deep(.grid-item.image-item.ant-image-img) {
  border-radius: 10px !important;
  width: 100% !important;
  height: 100% !important;
  aspect-ratio: 1 / 1; /* 强制正方形 */
  object-fit: cover !important;
}

.action-button {
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: #666;
  padding: 4px 10px;
  margin: 4px;
  border-radius: 20px;
  transition: all 0.2s ease;
}

.action-button:hover {
  color: #398bfb;
  background-color: #efefef;
}

.action-icon {
  margin-right: 20px;
}

.like-animation {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 60px;
  opacity: 0.8;
  pointer-events: none;
  z-index: 9999;
  transition: all 0.5s ease-out;
}

.like-enter-active,
.like-leave-active {
  transform: translate(-50%, -50%) scale(1);
  opacity: 1;
}
.like-enter-from,
.like-leave-to {
  transform: translate(-50%, -50%) scale(0);
  opacity: 0;
}

.comment-wrapper {
  clear: both;
  width: 100%;
  max-height: 350px; /* 设置最大高度 */
  overflow-y: auto; /* 超出后显示垂直滚动条 */
  margin-top: 8px;
  padding-top: 8px;
  scrollbar-width: thin; /* Firefox：细滚动条 */
}

:deep(.single-image.ant-image-img) {
  max-width: 100%;
  max-height: 300px;
  width: auto !important;
  height: auto !important;
  object-fit: contain !important;
}
</style>
